package com.wg.msorderds.controller;

import com.wg.msorderds.Maaper.OrderDetailsMapper;
import com.wg.msorderds.entity.*;
import com.wg.msorderds.entity.DTO.CreateOrderRequest;
import com.wg.msorderds.service.IOrdertbService;
import com.wg.msorderds.service.IUserAddressService;
import com.wg.msorderds.service.ProductFeignClient;
import com.wg.msorderds.serviceImp.OrdertbServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/order/ordertb")
public class OrdertbController {

    @Autowired
    private IOrdertbService ordertbService;
    @Autowired
    private OrderDetailsMapper orderDetailsMapper;
    @Autowired
    private ProductFeignClient productFeignClient; // 注入Feign客户端
    @Autowired
    private IUserAddressService userAddressService; // 添加地址服务依赖

    @Autowired
    private OrdertbServiceImpl ordertbServiceImpl;

    /**
     * 创建完整订单（包含订单详情）
     */
    @PostMapping("/create")
    public int createOrder(@RequestBody CreateOrderRequest request) {
        // 修改service方法使其返回创建的订单ID
        return ordertbService.createOrder(request.getOrder(), request.getOrderDetails());
    }
    /**
     * 根据ID获取完整订单信息（包含订单详情和商品信息）
     */
    @GetMapping("/get-full/{id}")
    public CreateOrderRequest getFullOrder(@PathVariable Integer id) {
        try {
            // 获取订单主信息
            Ordertb order = ordertbService.getById(id);
            if (order == null) {
                throw new RuntimeException("订单不存在，ID: " + id);
            }

            // 获取订单详情
            List<OrderDetails> orderDetails = orderDetailsMapper.selectByOrderId(id);

            // 通过Feign获取商品信息
            List<Product> products = new ArrayList<>();
            for (OrderDetails detail : orderDetails) {
                try {
                    System.out.println("正在获取商品信息，商品ID: " + detail.getProductId());
                    Product product = productFeignClient.getProductById(detail.getProductId());
//                    String product = productFeignClient.getProductByIdAsString(detail.getProductId());
                    if (product != null) {
                        System.out.println("成功获取商品信息，商品ID: " + product);
                        products.add(product);
                    }
                } catch (Exception e) {
                    // 记录日志，但不中断整个流程
                    System.err.println("获取商品信息失败，商品ID: " + detail.getProductId() + ", 错误: " + e.getMessage());
                }
            }
            // 获取地址信息
            UserAddress address = null;
            if (order.getAddressId() != null) {
                try {
                    address = userAddressService.getById(order.getAddressId());
                } catch (Exception e) {
                    System.err.println("获取地址信息失败，地址ID: " + order.getAddressId() + ", 错误: " + e.getMessage());
                }
            }

            // 返回完整订单信息
            return new CreateOrderRequest(order, orderDetails, products,address);
        } catch (Exception e) {
            throw new RuntimeException("获取订单信息失败: " + e.getMessage());
        }
    }

    // ... 其他方法
    /**
     * 添加订单
     */
    @PostMapping("/add")
    public boolean save(@RequestBody Ordertb ordertb) {
        boolean result = ordertbService.save(ordertb);
        return result;
    }

    /**
     * 删除订单
     */
    @DeleteMapping("/delete")
    public boolean delete(Integer id) {
        return ordertbService.removeById(id);
    }

    /**
     * 更新订单
     */
    @PutMapping("/update")
    public boolean update(@RequestBody Ordertb ordertb) {
        return ordertbService.updateById(ordertb);
    }

    /**
     * 根据ID获取订单
     */
    @GetMapping("/get")
    public Ordertb get(Integer id) {
        return ordertbService.getById(id);
    }

    /**
     * 获取所有订单列表
     */
    @GetMapping("/list")
    public List<Ordertb> list() {
        return ordertbService.list();
    }

    @PutMapping("/update/{orderId}")
    public int updateStatus(@PathVariable("orderId") Integer orderId) {
        return ordertbServiceImpl.updateStatusToPaid(orderId);
    }
    @GetMapping("/get-by-user/{userId}")
    public List<OrderProductInfo> getByUser(@PathVariable("userId") Integer userId) {
        return ordertbServiceImpl.getAllOrders(userId);
    }
}

